package models

import (
	"gorm.io/gorm"
)

type Novel struct {
	gorm.Model
	Title  string
	Author string
	Images string
	UserId int
	Status string
}

type Reads struct {
	Novel
	Username string
}

func (n *Novel) Create() error {
	return DB.Create(&n).Error
}

func (n *Novel) List(page, pageSize int) (list []Reads, err error) {

	err = DB.Table("novels").
		Select("novels.*,users.account as username").
		Scopes(Paginate(page, pageSize)).
		Joins("left join users on novels.user_id=users.id").
		Find(&list).Error
	return

}

func Paginate(page, pageSize int) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		if page <= 0 {
			page = 1
		}

		switch {
		case pageSize > 100:
			pageSize = 100
		case pageSize <= 0:
			pageSize = 5
		}

		offset := (page - 1) * pageSize
		return db.Offset(offset).Limit(pageSize)
	}
}

func (n *Novel) GetAccountById() error {
	return DB.Where("id=?", n.ID).Limit(1).Find(&n).Error
}

func (n *Novel) Del() error {
	return DB.Delete(&n).Error
}
